#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<cstdlib>
#include<unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<strings.h>


using namespace std;

void Usage(string proc)
{
    cout<<"Usage : "<<proc<<"serverip serverport"<<endl;
}

//./udpclient serverip serverport
int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0); 
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        cout<<"sockfd error"<<endl;
        return 1;
    }

    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    socklen_t len = sizeof(server);

    char buffer[1024];
    string message;

    while(true)
    {
        cout<<"please Enter@ ";
        getline(cin, message);
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&server, len);

        struct sockaddr_in temp;
        socklen_t lent = sizeof(temp);
        //输出型参数
        ssize_t s = recvfrom(sockfd, buffer, 1023, 0, (struct sockaddr*)&temp, &lent);
        if(s>0)
        {
            buffer[s] = 0;
            cout<<buffer<<endl;
        }
    }

    close(sockfd);

    return 0;
}